package springboot.app.conf ;

import java.io.IOException ;
import java.util.Properties ;

import javax.sql.DataSource ;

import org.apache.ibatis.plugin.Interceptor ;
import org.mybatis.spring.SqlSessionFactoryBean ;
import org.springframework.beans.factory.annotation.Qualifier ;
import org.springframework.context.annotation.Bean ;
import org.springframework.context.annotation.Configuration ;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver ;
import org.springframework.core.io.support.ResourcePatternResolver ;

import com.github.pagehelper.PageHelper ;

/**
 * 配置自己的SqlSessionFactory
 * @author 80002165 @date 2017年7月7日 上午11:45:38
 */
@Configuration
public class SqlSessionFactoryConfig {
    
    /* mybatis的mapper配置文件路径 */
    private static String MAPPER_PATH = "springboot/app/dao/mapper/*_mapper.xml" ;
    
    @Bean
    public PageHelper pageHelper(){
        PageHelper pageHelper = new PageHelper() ;
        Properties props = new Properties() ;
        props.put("helperDialect", "mysql") ;
        props.put("reasonable", "true") ;
        props.put("supportMethodsArguments", "true") ;
        props.put("autoRuntimeDialect", "true") ;
        props.put("returnPageInfo", "check") ;
        props.setProperty("params", "count=countSql") ;
        pageHelper.setProperties(props) ;
        return pageHelper ;
    }
    
    /**
     * mybatis配置sqlSessionFactory
     * @author 80002165 @date 2017年8月1日 下午4:34:41
     * @param dataSource
     * @return
     * @throws IOException
     */
    @Bean(value = "sqlSessionFactoryBean")
    public SqlSessionFactoryBean createSqlSessionFactoryBean(@Qualifier("dataSource") DataSource dataSource) throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean() ;
        sqlSessionFactoryBean.setDataSource(dataSource) ;
        
        // 添加分页插件
        /*
        PageHelper pageHelper = new PageHelper() ;
        Properties props = new Properties() ;
        props.put("helperDialect", "mysql") ;
        props.put("reasonable", "true") ;
        props.put("supportMethodsArguments", "true") ;
        props.put("autoRuntimeDialect", "true") ;
        props.put("returnPageInfo", "check") ;
        props.setProperty("params", "count=countSql") ;
        pageHelper.setProperties(props) ;
        sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageHelper});
        */
        PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver() ;
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + MAPPER_PATH ;
        
        sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResources(packageSearchPath)) ;
        return sqlSessionFactoryBean ;
    }
}
